package pt.ipl.isel.deetc.leic.pdm.g12.yamba;

import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

public class StatusToPostProvider extends ContentProvider {
	public static final String AUTHORITY = "pt.isel.deetc.leic.pdm.g12.yamba.providers";
	public static final Uri CONTENT_URI =  Uri.parse(ContentResolver.SCHEME_CONTENT+"://"+AUTHORITY);
	private static final String MIME_STATUS_ALL = "vnd.android.cursor.dir/vnd.isel.pdm.STATUS";
	private static final String MIME_STATUS_ONE = "vnd.android.cursor.item/vnd.isel.pdm.STATUS";
	
	private StatusHelper hdb;
    
	private static final int STATUS_ALL = 1;
    private static final int STATUS_ID = 2;

    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    
    static {
    	uriMatcher.addURI(AUTHORITY, "STATUS", STATUS_ALL);
    	uriMatcher.addURI(AUTHORITY, "STATUS/#", STATUS_ID);
    } 
    
	@Override
	public boolean onCreate() {
		Log.v("PDMG12","StatusToPostProvider: onCreate()");
		hdb = new StatusHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] proj, String sel, String[] selArgs, String sort) {
		sel = makeSelection(uri, sel);
		SQLiteDatabase db = hdb.getReadableDatabase();
		return db.query(StatusToPostContract.TABLE, proj, sel, selArgs, null, null, sort);
	}

	private String makeSelection(Uri uri, String sel) {
		switch (uriMatcher.match(uri)) {
		  case STATUS_ID:	return StatusToPostContract._ID + "=" + uri.getLastPathSegment();
		  default: return sel;
		}
	}
	
	@Override	
	public String getType(Uri uri) {
		return uriMatcher.match(uri)==STATUS_ALL ? MIME_STATUS_ALL : MIME_STATUS_ONE;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		Log.v("PDMG12","StatusToPostProvider: insert");
		SQLiteDatabase db = hdb.getWritableDatabase();
		try {
			long row = db.insert(StatusToPostContract.TABLE, null, values);
			return (row==-1) ? null : ContentUris.withAppendedId(uri, row);	
		} finally { db.close();	}
	}

	@Override
	public int delete(Uri uri, String sel, String[] selArgs) {
		SQLiteDatabase db = hdb.getWritableDatabase();
		try {
		  sel = makeSelection(uri, sel);
		  return db.delete(StatusToPostContract.TABLE, sel, selArgs);
		} finally {	db.close();	}
	}

	@Override
	public int update(Uri uri, ContentValues values, String sel, String[] selArgs) {
		SQLiteDatabase db = hdb.getWritableDatabase();
		try {
			sel = makeSelection(uri, sel);
			return db.update(StatusToPostContract.TABLE, values, sel, selArgs);
		} finally {	db.close();	}
	}
}
